package com.menu.Configuration;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.*;


@Configuration
@Getter
public class AlipayConfig {

    @Value("${open_api_domain}")
    private String open_api_domain;
    @Value("${appid}")
    private String appid;
    @Value("${alipay_public_key}")
    private String alipay_public_key;
    @Value("${sign_type}")
    private String sign_type;
    @Value("${NotifyUrl}")
    private String NotifyUrl;
    @Value("${ReturnUrl}")
    private String ReturnUrl;
    @Value("publicKey")
    private String publicKey;
    @Value("${sellerid}")
    private String sellerId;

    @Bean
    public AlipayClient alipayClient(){
            String privateKey = null;
            ClassPathResource classPathResource =
                    new ClassPathResource("privateKey.txt");
            try ( InputStream inputStream = classPathResource.getInputStream();
                  InputStreamReader isr = new InputStreamReader(inputStream);
                  BufferedReader bufferedReader = new BufferedReader(isr);){
                privateKey = bufferedReader.readLine();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
            if (privateKey == null){
                throw new RuntimeException("私钥为空！");
            }
        AlipayClient alipayClient =
                new DefaultAlipayClient(open_api_domain, appid, privateKey, "json", "UTF-8",alipay_public_key, sign_type);
        return alipayClient;
    }

    @Bean
    public AlipayTradePagePayRequest alipayTradePagePayRequest(){
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
        alipayTradePagePayRequest.setReturnUrl(ReturnUrl);
        alipayTradePagePayRequest.setNotifyUrl(NotifyUrl);
        return alipayTradePagePayRequest;
    }
}
